package br.brpv.silvestrin.conferencia.activity;

import br.brpv.silvestrin.conferencia.R;
import br.brpv.silvestrin.conferencia.activity.settings.SettingListActivity;
import br.brpv.silvestrin.conferencia.helper.ShowMessage;
import br.brpv.silvestrin.conferencia.models.User;
import br.brpv.silvestrin.conferencia.webservice.LoginWebservice;
import br.brpv.silvestrin.conferencia.webservice.LoginWebservice.LoginwebserviceListener;
import br.brpv.silvestrin.conferencia.webservice.Webservice.Status;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity implements OnClickListener, LoginwebserviceListener {

	private static final String LOGIN_SHARED_PREFERENCES = "loginSharedPreferences";
	private static final String LOGIN_REMEMBER_USER = "loginRememberUser";
	private static final String LOGIN_REMEMBER_PASSWORD = "loginRememberPassword";
	private static final String LOGIN_USER = "loginUser";
	private static final String LOGIN_PASSWORD = "loginPassword";
	
	
	private EditText userEdit;
	private EditText passwordEdit;
	private CheckBox rememberUserCheckBox;
	private CheckBox rememberPasswordCheckBox;
	private Button loginButton;
	
	private LoginWebservice webservice;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		initializeLayout();
		
		webservice = new LoginWebservice(this, this);
		
        setAppVersion();        
	}

	private void initializeLayout() {
		userEdit = (EditText) findViewById(R.id.login_edit_text);
        passwordEdit = (EditText) findViewById(R.id.password_edit_text);
        
        rememberUserCheckBox = (CheckBox)findViewById(R.id.remember_username_check_box);
        rememberPasswordCheckBox = (CheckBox)findViewById(R.id.remember_password_check_box);
        
        loginButton = (Button)findViewById(R.id.login_button);
        loginButton.setOnClickListener(this);
        
        initUserAndPassword();		
	}

	private void initUserAndPassword() {
		SharedPreferences preferences = this.getSharedPreferences(LOGIN_SHARED_PREFERENCES, 0);
        
        rememberUserCheckBox.setChecked(preferences.getBoolean(LOGIN_REMEMBER_USER, false));
        rememberPasswordCheckBox.setChecked(preferences.getBoolean(LOGIN_REMEMBER_PASSWORD, false));
        
        if(rememberUserCheckBox.isChecked() || rememberPasswordCheckBox.isChecked()){
        	userEdit.setText(preferences.getString(LOGIN_USER, ""));

            if(rememberPasswordCheckBox.isChecked()){
            	passwordEdit.setText(preferences.getString(LOGIN_PASSWORD, ""));
            }
        }		
	}

	private void setAppVersion() {
		TextView version = (TextView)findViewById(R.id.version_label);
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            version.setText("Version - " + pInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            
            case R.id.action_settings:
                Intent iSettings = new Intent(getApplicationContext(),
                        SettingListActivity.class);
                startActivity(iSettings);
                break;

            case R.id.action_exit:
                finish();
                break;
        }
        return true;
    }

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.login_button:
			SharedPreferences preferences = getSharedPreferences(LOGIN_SHARED_PREFERENCES, 0);
	        SharedPreferences.Editor editor = preferences.edit();

	        editor.putBoolean(LOGIN_REMEMBER_USER, rememberUserCheckBox.isChecked());
	        editor.putBoolean(LOGIN_REMEMBER_PASSWORD, rememberPasswordCheckBox.isChecked());

	        editor.commit();
	        
	        if(webservice.initializeServer() == Status.FAIL) {
	        	ShowMessage.alertDialog(this, R.string.login_server_disconfigured);
	        } else {
	        	webservice.selectUser(userEdit.getText().toString(), passwordEdit.getText().toString());
	        	
	        }
			break;
		}
	}
	
	@Override
	public void onSelectUser(User user) {
		if(user == null){
            ShowMessage.alertDialog(this, R.string.login_authentication_fail);
        }else {
            SharedPreferences preferences = this.getSharedPreferences(LOGIN_SHARED_PREFERENCES, 0);
            SharedPreferences.Editor editor = preferences.edit();

            editor.putString(LOGIN_USER, userEdit.getText().toString());
            editor.putString(LOGIN_PASSWORD, passwordEdit.getText().toString());

            editor.commit();
            
            navigateToOriginActivity(user);           
        }
		
	}

	private void navigateToOriginActivity(User user) {
		Intent intent = new Intent(getApplicationContext(),
                OriginActivity.class);
		intent.putExtra(OriginActivity.LOGGED_USER_EXTRA, user);
        startActivity(intent);		
	}

	@Override
	public void onSelectUserServerError() {
		ShowMessage.alertDialog(this, R.string.wsmessage_server_unreachable);		
	}

}
